#ifdef __linux

#include "ThreadAffinityLinux.h"
#include <unistd.h>
#include <pthread.h>

bool ThreadAffinityLinux::setAffinity(quint64 threadId, const QSet<int> &processorIndexs)
{
    // 检查处理器编号是否合法
    if (processorIndexs.isEmpty())
    {
        return false;
    }

    long processorCount = sysconf(_SC_NPROCESSORS_CONF);
    foreach (auto index, processorIndexs)
    {
        if (processorCount - 1 < index ||
            0 > index)
        {
            return false;
        }
    }

    // 将cpu添加到集合中
    cpu_set_t mask;
    CPU_ZERO(&mask);
    foreach (auto i, processorIndexs)
    {
        CPU_SET(i, &mask);
    }

    // 设置cpu亲和性
    int ret = pthread_setaffinity_np(threadId, sizeof(mask), &mask);
    return !(ret < 0);
}

#endif
